#include "seq_rule.h"
#include "table.h"

using namespace fouine;
using namespace std;

SeqRule::SeqRule(const std::vector<RuleId>& rule_ids_)
:_rule_ids(rule_ids_)
{}

SeqRule::~SeqRule()
{};

Likelihood SeqRule::match(const String&, StrId start, StrLen length, const Table& table) const
{
	return _match_rec(_rule_ids.begin(), start, length, table);
}


Likelihood SeqRule::_match_rec(std::vector<RuleId>::const_iterator rule_it, StrId start, StrLen length, const Table& table) const
{
	if (rule_it == _rule_ids.end())
		return 1.;
	else 
	{
		Likelihood p = 0.;
		RuleId rule_id = *rule_it;
		for (StrLen c=1; c<length-1; c++) {
			Likelihood p_left = table(start, c, rule_id);
			if (p_left >= p) {
				const Likelihood p_right = _match_rec(++rule_it,start+c,length-c,table);
				p = max(p_left*p_right,p);
			}
		}
		return p;
	}
}


